package com.ftl.search.common.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class HttpClientUtils {
    /**
     * 有参数请求的get请求
     *
     * @param url      请求接口
     * @param paramList 请求参数List对象
     * @param headMap 请求的头
     * @return
     */
    public static Object getParamMap(String url, List<Map<String, String>> paramList, Map<String, String> headMap) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            List<NameValuePair> pairs = new ArrayList<>();
            for (Map<String, String> param: paramList) {
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            CloseableHttpResponse response;
            URIBuilder builder = new URIBuilder(url).addParameters(pairs);
            // 执行get请求.
            HttpGet httpGet = new HttpGet(builder.build());
            if (!CollectionUtils.isEmpty(headMap)) {
                headMap.forEach(httpGet::addHeader);
            }
            response = httpClient.execute(httpGet);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (MediaType.APPLICATION_JSON.toString().equals(entity.getContentType().getValue())) {
                    String jsonString = EntityUtils.toString(entity);
                    return JSON.parse(jsonString);
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("请求第三方失败：{}", e.getMessage());
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                log.info("释放资源失败：{}", e.getMessage());
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 发送post请求，参数用map接收
     *
     * @param url    地址
     * @param json 请求的对象
     * @param headMap 请求的头
     * @return 返回值
     */

    public static Object postMap(String url, String json, Map<String, String> headMap) {
        //获取json字符串
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response;
        try {
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            if (!CollectionUtils.isEmpty(headMap)) {
                headMap.forEach(httpPost::addHeader);
            }
            response = httpClient.execute(httpPost);
            if (response != null && (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201)) {
                HttpEntity entity = response.getEntity();
                String jsonString = EntityUtils.toString(entity);
                return JSON.parse(jsonString);
            }
        } catch (Exception e) {
            log.info("请求第三方失败：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                log.info("释放资源失败：{}", e.getMessage());
                e.printStackTrace();
            }
        }
        return null;
    }
}
